package com.example.origin.finance.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.origin.finance.dto.BaseTable;
import com.example.origin.finance.enums.TableNameEnum;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public abstract class AbstractStoreService<T extends BaseTable> extends AbstractUtilService {

    @SneakyThrows
    public void storeTable(List<String> list, TableNameEnum tableNameEnum) {
        String name = tableNameEnum.getTable();
        int size = list.size();
        boolean flag = size == 1;

        if (!flag) {
            mongoTemplate.dropCollection(name);
        }

        if (flag || !mongoTemplate.collectionExists(name)) {
            List<T> quotes = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                String code = list.get(i);
                T quote = getData(code);
                if (quote != null && !ObjectUtil.isEmpty(quote.getCode())) {
                    quotes.add(quote);
                    logProcess(i, size);
                }
            }
            if (flag && mongoTemplate.collectionExists(name)) {
                mongoTemplate.remove(Query.query(Criteria.where("code").is(quotes.get(0).getCode())), name);
            }
            mongoTemplate.insert(quotes, name);
            if (!flag) {
                createIndex(name);
            }
        }
    }

    protected abstract T getData(String code);


}
